<template>
    <div>
        <el-row>
            <el-col :span="11">
                <div class="chart">
                    <Echarts :options="chartOptions1" />
                </div>
            </el-col>
            <el-col :span="11" :offset="1">
                <div class="chart">
                    <Echarts :options="chartOptions2" />
                </div>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="11">
                <div class="chart">
                    <Echarts :options="chartOptions3" />
                </div>
            </el-col>
            <el-col :span="11" :offset="1">
                <div class="chart">
                    <Echarts :options="chartOptions4" />
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import Echarts from "@/components/Echarts.vue";
import { reactive, onMounted } from "vue";
import axios from "axios";
import dayjs from "dayjs";

// 响应式图表配置
const chartOptions1 = reactive({
  title: {
    text: "近一个月每日新注册用户数",
    left: "center"
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  },
  xAxis: {
    type: "category",
    data: [] // 动态填充日期数据
  },
  yAxis: {
    type: "value",
    name: "新注册用户数"
  },
  series: [
    {
      name: "新注册用户数",
      type: "line",
      data: [] // 动态填充每日注册数
    }
  ]
});

const chartOptions2 = reactive({
    title: {
        text: "近一个月每日发帖/服务数",
        left: "center"
    },
    tooltip: {
        trigger: "axis",
        axisPointer: {
            type: "shadow"
        }
    },
    xAxis: {
        type: "category",
        data: [] // 动态填充日期数据
    },
    yAxis: {
       type: "value",
    },
    legend: {
        data: ["发帖数", "服务数"],
        //位置
        left: "left",
    },
    series: [
        {
            name: "发帖数",
            type: "line",
            data: [] // 动态填充每日发帖数
        },
        {
            name: "服务数",
            type: "line",
            data: [] // 动态填充每日服务数
        }
    ]
});

const chartOptions3 = reactive({
  title: {
    text: "用户年龄分布",
    left: "center",
  },
  tooltip: {
    trigger: "item",
  },
  legend: {
    bottom: "0%",
    left: "center",
  },
  series: [
    {
      name: "用户数量",
      type: "pie",
      radius: "50%",
      data: [], // 数据会在请求后填充
    },
  ],
});

const chartOptions4 = reactive({
  title: {
    text: "用户城市分布",
    left: "center",
  },
  tooltip: {
    trigger: "item",
  },
  legend: {
    bottom: "0%",
    left: "center",
  },
  series: [
    {
      name: "用户数量",
      type: "pie",
      radius: "50%",
      data: [], // 数据会在请求后填充
    },
  ],
});


// 工具函数：生成连续日期范围
const generateDateRange = (startDate, endDate) => {
  const dates = [];
  let currentDate = dayjs(startDate);

  while (currentDate.isBefore(endDate) || currentDate.isSame(endDate)) {
    dates.push(currentDate.format("YYYY-MM-DD")); // 确保格式一致
    currentDate = currentDate.add(1, "day");
  }
  return dates;
};


const getLastMonthRange = () => {
  const endDate = dayjs().endOf("day"); // 以今天为结束日期
  const startDate = endDate.subtract(30, "days"); // 开始日期减30天
  return generateDateRange(startDate, endDate);
};


// 获取每日注册数据并更新图表
const fetchDailyRegistrations = async () => {
  try {
    const response = await axios.get("http://localhost:8088/users/getDailyRegistrations");
    const data = response.data;

    const receivedData = {};
    data.forEach((item) => {
      receivedData[item.reg_date] = item.count;
    });

    const dateRange = getLastMonthRange();
    // 补全日期数据
    const dates = [];
    const counts = [];
    dateRange.forEach((date) => {
        dates.push(date);
        counts.push(receivedData[date] ?? 0); // 如果 `receivedData[date]` 是 undefined 或 null，使用 0
    });

    console.log(counts);
    console.log(dates);

    // 更新图表数据
    chartOptions1.xAxis.data = dates;
    chartOptions1.series[0].data = counts;
  } catch (error) {
    console.error("获取每日注册数据失败：", error);
  }
};

const getPostCount = async () => {
    try {
        const response = await axios.get("http://localhost:8088/posts/getDailyPosts");
        const data = response.data;

        const receivedData = {};
        data.forEach((item) => {
        receivedData[item.post_date] = item.count;
        });

        const dateRange = getLastMonthRange();
        // 补全日期数据
        const dates = [];
        const counts = [];
        dateRange.forEach((date) => {
            dates.push(date);
            counts.push(receivedData[date] || 0); // 如果没有数据，填充为0
        });

        console.log(counts);
        console.log(dates);


        // 更新图表数据
        chartOptions2.xAxis.data = dates;
        chartOptions2.series[0].data = counts;
    }catch(error) {
        console.error("获取每日发帖数据失败：", error);
    }
};

const getServiceCount = async () => {
    try {
        const response = await axios.get("http://localhost:8088/services/getDailyServices");
        const data = response.data;

        const receivedData = {};
        data.forEach((item) => {
        receivedData[item.post_date] = item.count;
        });

        const dateRange = getLastMonthRange();
        // 补全日期数据
        const dates = [];
        const counts = [];
        dateRange.forEach((date) => {
            dates.push(date);
            counts.push(receivedData[date] || 0); // 如果没有数据，填充为0
        });


        // 更新图表数据
        chartOptions2.series[1].data = counts;
    }catch(error) {
        console.error("获取每日服务数据失败：", error);
    }
};

const fetchAgeDistribution = async () => {
  try {
    const response = await axios.get("http://localhost:8088/users/getAgeDistribution");
    const data = response.data;

    // 格式化数据
    const formattedData = data.map((item) => ({
      name: item.age_group,
      value: item.user_count,
    }));

    // 更新图表数据
    chartOptions3.series[0].data = formattedData;
  } catch (error) {
    console.error("获取年龄分布数据失败：", error);
  }
};

const fetchCityDistribution = async () => {
  try {
    const response = await axios.get("http://localhost:8088/cities/getCityDistribution");
    const data = response.data;

    // 格式化数据
    const formattedData = data.map((item) => ({
      name: item.cityName,
      value: item.userCount,
    }));

    // 更新图表数据
    chartOptions4.series[0].data = formattedData;
  } catch (error) {
    console.error("获取城市分布数据失败：", error);
  }
};

onMounted(() => {
  fetchDailyRegistrations();
  getPostCount();
  getServiceCount();
  fetchAgeDistribution();
  fetchCityDistribution();
});
</script>

<style scoped>
.chart {
    height: 100%;
    width: 100%;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 10px;
}

</style>